package com.xuanwu.ai.flow.component;

import com.alibaba.fastjson.JSONObject;
import com.xuanwu.ai.flow._enum.ErrorCodeEnum;
import com.xuanwu.ai.flow.constant.GlobalConstant;
import com.xuanwu.ai.flow.dto.CmpDataDTO;
import com.xuanwu.ai.flow.dto.CommonContextDTO;
import com.xuanwu.ai.flow.sao.AIDetectSao;
import com.xuanwu.ai.flow.sao.req.ImageMergeReq;
import com.xuanwu.ai.flow.utils.NodeDataUtils;
import com.xuanwu.ai.web.exception.BizException;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@LiteflowComponent(name = "图片拼接SKU识别组件", value = "imageMergeCmp")
@Slf4j
public class ImageMergeCmp extends NodeComponent {
    @Autowired
    private AIDetectSao aiDetectSao;

    @Override
    public void process() throws Exception {
        CommonContextDTO customContext = this.getContextBean(CommonContextDTO.class);
        if (customContext.getToken() == null) {
            throw new BizException(ErrorCodeEnum.NO_VALID_TOKEN);
        }
        ImageMergeReq imageMergeReq = new ImageMergeReq();
        List<String> urls = customContext.getUrls() == null ? new ArrayList<>() : customContext.getUrls();
        List<Map<String, String>> imageData = new ArrayList<>();
        for (String url : urls) {
            Map<String, String> urlMap = new HashMap<>();
            urlMap.put("url", url);
            imageData.add(urlMap);
        }
        imageMergeReq.setImageData(imageData);
        JSONObject jsonObject = aiDetectSao.imageMerge(customContext.getToken(), imageMergeReq);
        log.info("图片拼接SKU识别结果:{}", jsonObject.getString("data"));

        //识别成功则封装成json数据
        if (jsonObject.get("status").equals(GlobalConstant.CMP_EXECUTE_SUCCESS)) {
            Map<String, String> mergeResultMap = new HashMap<>();
            mergeResultMap.put("mergeResult", jsonObject.getString("data"));
            jsonObject.remove("data");
            jsonObject.put("data", mergeResultMap);
        }

        // 设置节点数据
        NodeDataUtils.setStepNodeData(customContext, this.getCmpData(CmpDataDTO.class).getUuid(), this.getName(), jsonObject);

        if(jsonObject.getInteger("status").equals(GlobalConstant.CMP_EXECUTE_FAIL)){
            throw new BizException(ErrorCodeEnum.CMP_EXECUTE_FAIL, this.getName());
        }
    }
}
